import { defineStore } from 'pinia'
import http from '@/tools/http'

interface Dict {
    dicts: DictItem[]
}

interface DictItem {
    dictCode: string,
    dictItemName: string,
    dictItemValue: string
}

export const useDictStore = defineStore('dict', {
    state: (): Dict => ({ dicts: [] }),
    getters: {
        dict: (state) => {
            return (dictCode: string) => {
                return state.dicts.filter(dictItem => dictItem.dictCode === dictCode).map(dictItem => {
                    return {
                        label: dictItem.dictItemName,
                        value: dictItem.dictItemValue
                    }
                })
            }
        },
        dictItem: (state) => {
            return (dictCode: string, dictItemValue: string | undefined) => {
                if (dictItemValue) {
                    for (let i = 0; i < state.dicts.length; i++) {
                        if (state.dicts[i].dictCode === dictCode && state.dicts[i].dictItemValue === dictItemValue) {
                            return state.dicts[i].dictItemName
                        }
                    }
                }
                return ""
            }
        }
    },
    actions: {
        refresh() {
            const req = { pageNum: 0, pageSize: 0 }
            http.post("/dictionary/item/page", req).then(({ data }) => {
                if (data.code === "0") {
                    this.dicts.length = 0
                    for (let i = 0; i < data.data.list.length; i++) {
                        this.dicts.push(data.data.list[i])
                    }
                }
            })
        }
    }
})